package com.sys.manage.service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.sys.api.Service.OrderManagerService;
import com.sys.common.ZuelResult;
import com.sys.manage.dao.OrderContentDao;
import com.sys.manage.dao.OrderInfoDao;
import com.sys.manage.dao.UserDao;
import com.sys.pojo.OrderContent;
import com.sys.pojo.OrderInfo;
import com.sys.pojo.OrderUser;
import com.sys.vo.OrderAll;
import com.sys.vo.OrderResponse;
import com.sys.vo.OrdersList;

@Service
@CacheConfig(cacheNames="order")
public class OrderManagerServiceImpl implements OrderManagerService {

	@Autowired
	private OrderInfoDao infoDao;
	
	@Autowired
	private OrderContentDao contentDao;
	
	@Autowired
	private UserDao userdao;

	@Autowired
    private RedisTemplate<String, Object> redisTemplate;
	
	@Override
	public ZuelResult responseOrder(OrderResponse res) {
		// TODO Auto-generated method stub
		if (res==null || res.getContent().trim()==null) {
			return ZuelResult.error(null, "不要填空");
		}
		OrderContent content = new OrderContent();
		content.setOid(res.getOrderId());
		content.setContent(res.getContent());
		content.setCreatetime(new Date(System.currentTimeMillis()));
		content.setRole(2);
		contentDao.save(content);
		String keyTemp = "order::getAllOrder(" + res.getOrderId() + ")";
		boolean k =redisTemplate.delete(keyTemp);
		System.out.println(k);
		return ZuelResult.ok(content, "回复成功");
	}

	@Override
	@Cacheable(key="'getAllOrder('+#id+')'")
	public OrderAll getAllOrder(int id) {
		// TODO Auto-generated method stub
		OrderAll all = new OrderAll();
		Optional<OrderInfo>  optional = infoDao.findById(id);
		OrderInfo info  = optional.get();
		all.setInfo(info);
		all.setContents(contentDao.findByOid(id));
		all.setManagerName("admin");
		Optional<OrderUser> optional2 = userdao.findById(info.getUid());
		OrderUser user = optional2.get();
		all.setUname(user.getUsername());
		if (info.getState().equals("1")) {
			all.getInfo().setState("进行中");
		}
		if (info.getState().equals("0")) {
			all.getInfo().setState("已结束");
		}
		return all;
	}

	@Override
	@Cacheable(key="'getOrdersList()'")
	public OrdersList getOrdersList() {
		// TODO Auto-generated method stub
		List<OrderInfo> infos= infoDao.findAll();
		for (int i = 0; i < infos.size(); i++) {
			if (infos.get(i).getState().equals("1")) {
				infos.get(i).setState("进行中");
			}
			if (infos.get(i).getState().equals("0")) {
				infos.get(i).setState("已结束");
			}
		}
		OrdersList list =new OrdersList();
		list.setInfoList(infos);
		list.setManagerName("admin");
		return list;
	}
	
	
}
